import React, { useRef, useEffect, useState } from 'react';
import { X, MessageSquare } from 'lucide-react';
import { useAIChat } from '@/contexts/aiChat';
import MessageList from '@/components/aiChat/MessageList';
import MessageInput from '@/components/aiChat/MessageInput';
import ChatSidebar from '@/components/aiChat/ChatSidebar';

/**
 * 聊天窗口组件
 * 显示聊天界面，包括头部、消息列表和输入区域
 */
const ChatWindow: React.FC = () => {
  const { isOpen, closeChat } = useAIChat();
  const windowRef = useRef<HTMLDivElement>(null);
  const resizeHandleRef = useRef<HTMLDivElement>(null);
  
  // 窗口位置和大小状态
  const [position, setPosition] = useState({ x: window.innerWidth - 520, y: window.innerHeight - 650 });
  const [size, setSize] = useState({ width: 480, height: 600 });
  const [isDragging, setIsDragging] = useState(false);
  const [isResizing, setIsResizing] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  
  // 注意：closeChat 已在上面解构
  
  // 处理拖动开始
  const handleDragStart = (e: React.MouseEvent<HTMLDivElement>) => {
    const dragHandle = windowRef.current?.querySelector('.drag-handle');
    if (dragHandle && dragHandle.contains(e.target as Node)) {
      setIsDragging(true);
      setDragOffset({
        x: e.clientX - position.x,
        y: e.clientY - position.y
      });
    }
  };
  
  // 处理拖动
  useEffect(() => {
    const handleDragMove = (e: MouseEvent) => {
      if (isDragging) {
        setPosition({
          x: Math.max(0, Math.min(window.innerWidth - size.width, e.clientX - dragOffset.x)),
          y: Math.max(0, Math.min(window.innerHeight - size.height, e.clientY - dragOffset.y))
        });
      }
    };
    
    const handleDragEnd = () => {
      setIsDragging(false);
    };
    
    if (isDragging) {
      document.addEventListener('mousemove', handleDragMove);
      document.addEventListener('mouseup', handleDragEnd);
    }
    
    return () => {
      document.removeEventListener('mousemove', handleDragMove);
      document.removeEventListener('mouseup', handleDragEnd);
    };
  }, [isDragging, dragOffset, size]);
  
  // 处理调整大小
  const handleResizeStart = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsResizing(true);
  };
  
  useEffect(() => {
    const handleResizeMove = (e: MouseEvent) => {
      if (isResizing) {
        // 计算新的宽度和高度
        const newWidth = Math.max(300, Math.min(800, e.clientX - position.x));
        const newHeight = Math.max(400, Math.min(800, e.clientY - position.y));
        setSize({ width: newWidth, height: newHeight });
      }
    };
    
    const handleResizeEnd = () => {
      setIsResizing(false);
    };
    
    if (isResizing) {
      document.addEventListener('mousemove', handleResizeMove);
      document.addEventListener('mouseup', handleResizeEnd);
    }
    
    return () => {
      document.removeEventListener('mousemove', handleResizeMove);
      document.removeEventListener('mouseup', handleResizeEnd);
    };
  }, [isResizing, position]);

  if (!isOpen) return null;

  return (
    <div 
      ref={windowRef}
      className="fixed z-50 flex overflow-hidden bg-background border border-border rounded-lg shadow-xl"
      style={{
        left: `${position.x}px`,
        top: `${position.y}px`,
        width: `${size.width}px`,
        height: `${size.height}px`
      }}
      onMouseDown={handleDragStart}
      aria-modal="false"
      role="dialog"
    >
        {/* 侧边栏 */}
        <ChatSidebar />
        
        {/* 主聊天区域 */}
        <div className="flex-1 flex flex-col h-full">
          {/* 头部区域 - 可拖动 */}
          <div className="p-3 border-b flex items-center justify-between cursor-move drag-handle">
            <div className="flex items-center">
              <div className="w-8 h-8 rounded-full bg-primary/20 flex items-center justify-center">
                <MessageSquare className="w-4 h-4 text-primary" />
              </div>
              <div className="ml-2">
                <h3 className="font-medium text-sm">OnceOne 智能助手</h3>
                <div className="flex items-center text-xs text-muted-foreground">
                  <span className="w-1.5 h-1.5 rounded-full bg-green-500 mr-1"></span>
                  <span>在线</span>
                </div>
              </div>
            </div>
            <div className="flex items-center space-x-2">
              <button 
                onClick={closeChat}
                className="w-7 h-7 rounded-full hover:bg-accent flex items-center justify-center"
                aria-label="关闭对话"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          </div>
          
          {/* 消息列表区域 */}
          <MessageList />
          
          {/* 输入区域 */}
          <MessageInput />
        </div>
        
        {/* 调整大小的手柄 */}
        <div 
          ref={resizeHandleRef}
          className="absolute bottom-0 right-0 w-8 h-8 cursor-nwse-resize flex items-center justify-center text-muted-foreground hover:text-foreground"
          onMouseDown={handleResizeStart}
          aria-label="调整对话框大小"
        >
        </div>
      </div>
  );
};

export default ChatWindow;
